<?php
/**
 * @category Goatherd
 * @package Goatherd\Commons
 *
 * @author Copyright (c) 2012 Maik Penz <maik@phpkuh.de>
 * @version $Id: Collection.php 85 2012-03-27 22:34:52Z maik@phpkuh.de $
 *
 * This file is part of Goatherd library.
 *
 * Goatherd library is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Goatherd library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Goatherd library. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Goatherd\Commons\Collection;

/**
 * Full collection implementation.
 *
 * @category Goatherd
 * @package Goatherd\Commons
 * @subpackage Collection
 */
class Collection
extends \ArrayObject
implements ICollection
{
    /**
     * Entity base class/ interface.
     *
     * @var string
     */
    protected $_entityNamespace = '\\Goatherd\\Commons\\Collection\\IEntity';

    /**
     * (non-PHPdoc)
     * @see Goatherd\Commons\Collection.ICollection::getEntityNamespace()
     */
    public function getEntityNamespace()
    {
        return $this->_entityNamespace;
    }

    /**
     * (non-PHPdoc)
     * @see Goatherd\Commons\Collection.ICollection::clear()
     */
    public function clear()
    {
        return parent::exchangeArray(array());
    }

    /**
     * (non-PHPdoc)
     * @see ArrayObject::exchangeArray()
     */
    public function exchangeArray($array)
    {
        $old = $this->clear();

        foreach ($array as $key => $value) {
             $this->offsetSet($key, $value);
        }

        return $old;
    }

    /**
     * (non-PHPdoc)
     * @see ArrayAccess::offsetSet()
     */
    public function offsetSet ($offset, $value)
    {
        // TODO: might specify interfaces too!
        if (!is_object($value) && null !== $value) {
            throw new \InvalidArgumentException(sprintf("Value must be an object or null. '%s' given.", gettype($value)));
        } elseif (!($value instanceof $this->_entityNamespace)) {
            throw new \InvalidArgumentException(sprintf("Value must implement '%s'.", $this->_entityNamespace));
        }
        parent::offsetSet($offset, $value);
    }
}
